package com.eschool.beans;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import com.eschool.beans.converter.UserConverter;
import com.eschool.model.User;
import com.eschool.service.CustomerService;
import com.eschool.service.impl.CustomerServiceImpl;
import com.eschool.util.UserUtil;


@ManagedBean(name="updatePasswordBean")
@ViewScoped
public class UpdatePasswordBean {

	private User selectedUser;
	private List<User> allUsers;
	private UserConverter userConverter;
	CustomerService service = new CustomerServiceImpl();
	
	public UpdatePasswordBean() {
		selectedUser = new User();
		userConverter = new UserConverter(getCurrentUserRoleId());
		allUsers = UserConverter.users;
	}

	public User getSelectedUser() {
		return selectedUser;
	}

	public void setSelectedUser(User selectedUser) {
		this.selectedUser = selectedUser;
	}

	public List<User> getAllUsers() {
		return allUsers;
	}

	public void setAllUsers(List<User> allUsers) {
		this.allUsers = allUsers;
	}

	public UserConverter getUserConverter() {
		return userConverter;
	}

	public void setUserConverter(UserConverter userConverter) {
		this.userConverter = userConverter;
	}
	
	public List<User> completeUser(String query) {
		List<User> userSuggestions = new ArrayList<User>();  
        
        for(User u : allUsers) {  
            if(u.getName().toLowerCase().startsWith(query.toLowerCase().trim()))  
            	userSuggestions.add(u);  
        }  
          
        return userSuggestions; 
	}

	public String updatePassword() {

		if(service.updateUser(selectedUser))
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,null, "Password Updated Successfully"));
		else
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,null, "Password Not Updated"));
		
		return "UpdatePassword";
	}
	
	private int getCurrentUserRoleId() {
		if (UserUtil.currentAdmin() != null)
			return UserUtil.currentAdmin().getRole().getRoleId();
		
		return UserUtil.currentUser().getRole().getRoleId();
	}

}
